package com.nuanshui.heatedloan.dao.cms.security;

import com.nuanshui.heatedloan.constant.ManageGlobalParam;
import com.nuanshui.heatedloan.dal.IdTypeHandler;
import com.nuanshui.heatedloan.extension.hibernate.HibernateUtils;
import com.nuanshui.heatedloan.userinfo.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class FrontUseDaoImpl {
	
	@Autowired
	private HibernateUtils hibernateUtils;
	
	@Autowired
	private JdbcTemplate  jdbcTemplate;

	private Logger logger= LoggerFactory.getLogger(FrontUseDaoImpl.class);
	
	/**
	 * 获取app端的用户，根据用户手机号
	 * @author Gonzo
	 * @date 2017年1月12日下午8:22:23
	 * @param phone
	 * @return
	 * @since 1.0.0
	 */
	public User getFrontUserByPhone(String phone){
		String sql = "select id as idRaw, nick, phone, password  from " + ManageGlobalParam.USER_DB_SCHEMA +".users where phone = '" + phone +"'";
		User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class));
		return user;
	}

	/**
	 * 获取app端的用户，根据用户id
	 * @author Gonzo
	 * @date 2017年1月12日下午8:22:23
	 * @param userId
	 * @return
	 * @since 1.0.0
	 */
	public User getFrontUserByUserId(String userId) {
		String sql = "select id as idRaw, nick, phone, password from " + ManageGlobalParam.USER_DB_SCHEMA +".users where id = " + userId;
		User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class));
		return user;
	}

	/**
	 * 更新app端用户的密码
	 * @author Gonzo
	 * @date 2017年1月12日下午8:22:12
	 * @param frontUserId
	 * @param plainPassword
	 * @since 1.0.0
	 */
	public void updatePassWord(Integer frontUserId, String plainPassword) {
		String sql = "update " + ManageGlobalParam.USER_DB_SCHEMA +".users set password = '" + plainPassword + "' where id = '" + frontUserId + "'";
		jdbcTemplate.execute(sql);
	}
	
	/**
	 * 更新app端用户的昵称
	 * @author zhousishang
	 * @date 2017年4月28日下午12:36:12
	 * @param frontUserId
	 * @param nick
	 * @since 1.0.0
	 */
	public void updateNick(Integer frontUserId, String nick) {
		String sql = "update " + ManageGlobalParam.USER_DB_SCHEMA +".users set nick = '" + nick + "' where id = '" + frontUserId + "'";
		jdbcTemplate.execute(sql);
	}

	public List<Map<String,Object>> findByRoleName(String roleName){
		List<Map<String,Object>> lists=new ArrayList<Map<String,Object>>();
		String sql="select us.id,us.realname from cms_security_user us,cms_security_role role,cms_security_user_role usr " +
				"where role.name='"+roleName+"' and role.id=usr.role_id and usr.user_id=us.id";
		lists=jdbcTemplate.queryForList(sql);
		for(Map map:lists){
			Long id=(Long)map.get("id");
			String mixId= IdTypeHandler.encode(id);
			map.put("id",mixId);
		}
		return lists;
	}



}
